package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"time"

	"uploadsrv/helper"
	"uploadsrv/middle"

	"github.com/gin-gonic/gin"
)

var (
	port    = flag.Int("port", 9093, "upload server port")
	runPath string
)

func main() {
	flag.Parse()

	var err error
	runPath, err = helper.GetRunPath()
	if err != nil {
		log.Println("helper.GetRunPath failed, err=", err)
		return
	}

	engine := gin.Default()

	engine.Use(middle.CORS)
	engine.POST("/api/v1/upload", middle.CheckToken(), UploadFile)
	engine.Static("/download/", runPath+"/download")
	engine.GET("/v1/*all", Test)

	srvAddr := fmt.Sprintf(":%d", *port)
	log.Println("===== engine.Run at ", srvAddr)
	err = engine.Run(srvAddr)
	if err != nil {
		log.Println("engine.Run failed, err=", err)
		return
	}
	log.Println("===== engine.Run End ")
}

func Test(c *gin.Context) {
	c.JSON(200, gin.H{"path": c.Params.ByName("all")})
}

func UploadFile(c *gin.Context) {
	upFile, err := c.FormFile("file")
	if err != nil {
		log.Println("Get upload file failed, err=", err)
		return
	}

	now := time.Now()
	uploadPath := runPath + "/upload"

	_, err = os.Stat(uploadPath)
	if os.IsNotExist(err) {
		// Create parent directory if it does not exist
		if err = os.Mkdir(uploadPath, 0766); err != nil {
			log.Println("os.Mkdir failed, err=", err)
			return
		}
	} else if err != nil {
		log.Println("os.Stat failed, err=", err)
		return
	}

	fileName := fmt.Sprintf("%s/%d-%s", uploadPath, now.Unix(), upFile.Filename)
	err = c.SaveUploadedFile(upFile, fileName)
	if err != nil {
		log.Println("SaveUploadedFile failed, err=", err)
		return
	}
	log.Println("SaveUploadedFile success, filename=", fileName)
}
